﻿using AutoMapper;
using Customer.API.Applcation.Command.ProcurementStorageCommand;
using Customer.Domain;
using Customer.Infrstructre;
using Customer.Infrstructre.ProcurementManager;
using Customer.Infrstructre.ProcurementStorageManager;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Customer.API.Applcation.CommandHandlers.ProcurementStorageCommandHandler
{
    public class AddProcurementStorageCommandHandler : IRequestHandler<AddProcurementStorageCommand, int>
    {

        IProcurementStorageRepository psRep;
        IProcurementRepository pRep;
        IMapper _mapper;
        EFCoreDBcontext dbContext;

        public AddProcurementStorageCommandHandler(IProcurementStorageRepository psRep, IProcurementRepository pRep, IMapper _mapper, EFCoreDBcontext dbContext)
        {
            this.psRep = psRep;
            this._mapper = _mapper;
            this.dbContext = dbContext;
            this.pRep = pRep;
        }


        public async Task<int> Handle(AddProcurementStorageCommand request, CancellationToken cancellationToken)
        {
            using (var tran = await dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {

                try
                {
                    //添加采购入库
                    var procurement1 = _mapper.Map<ProcurementStorage>(request.addDto);
                    var taskToAdd = await psRep.AddAsync(procurement1);

                    //修改状态
                    var list = await pRep.GetModelAsync(request.addDto.ProcurementId);
                    list.ProcureState = request.addDto.ProcureState;
                    await pRep.Update(list);

                    // 提交事务
                    tran.Commit();

                    return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    tran.Rollback();
                    throw;
                }
            }

        }
    }
}
